package com.microtf.inscription.framework.service;

import com.microtf.inscription.jpa.UserJpa;
import com.microtf.inscription.jpa.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Optional;

/**
 * 用户服务
 *
 * @author guliuzhong
 */
@Service
@Slf4j
public class UserService extends BaseService {
    private UserJpa userJpa;
    PasswordEncoder passwordEncoder;

    @Autowired
    public void setUserJpa(UserJpa userJpa) {
        this.userJpa = userJpa;
    }

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 验证用户名密码
     * <p>验证完成后清空用户密码信息</p>
     *
     * @param userName 用户名
     * @param password 密码
     * @return 密码正确返回用户信息否则返回空
     */
    public Optional<User> validPassword(String userName, String password) {
        User user = getUser(userName);
        if (user == null) {
            return Optional.empty();
        }
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (matches) {
            User userCopy = new User();
            BeanUtils.copyProperties(user, userCopy);
            userCopy.setPassword("");
            return Optional.of(userCopy);
        }
        return Optional.empty();
    }

    /**
     * 获取用户
     * @param userName 用户名
     * @return 存在返回用户不存在返回空
     */
    public User getUser(String userName) {
        if (userName == null || userName.isEmpty()) {
            return null;
        }
        Optional<User> one = userJpa.findByUsername(userName);
        return one.orElse(null);
    }

    /**
     * 获取用户
     * @param userId 用户Id
     * @return 存在返回用户不存在返回空
     */
    public User getUser(Long userId) {
        if (userId == null || userId == 0) {
            return null;
        }
        Optional<User> one = userJpa.findById(userId);
        return one.orElse(null);
    }

    /**
     * 生成用户密码
     *
     * @param len      密码长度
     * @param readAble 是否可读
     * @return 生成的密码
     */
    public String generalPassword(int len, boolean readAble) {
        StringBuilder stringTab = new StringBuilder();
        if (!readAble) {
            stringTab.append("BCEFGHJKMPQRTVWXY2346789");
        } else {
            stringTab.append("ABCDEFGHJKMNPQRSTUVWXY0123456789abcdefghjkmnrstuvwxyz");
        }
        try {
            StringBuilder stringBuilder = new StringBuilder();
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            for (int i = 0; i < len; i++) {
                int number = secureRandom.nextInt(stringTab.length());
                stringBuilder.append(stringTab.substring(number, number + 1));
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("生成密码出错");
        }
        return null;
    }
}
